import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import moment from 'moment';

import { Form } from '@ant-design/compatible';

import {
  Card,
  Row,
  Col,
  Select,
  Checkbox,
  TimePicker,
  Timeline,
  message,
} from 'antd';
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';

import '@ant-design/compatible/assets/index.css';
import { DetailInfoItem } from '../data';
import styles from './style.less';

const { Option } = Select;
const { RangePicker } = TimePicker;
const { Item } = Form;

const reserveTimeBtn = {
  height: '32px',
  padding: '6px 4px',
  fontSize: '18px',
  cursor: 'pointer',
  border: '1px solid #d9d9d9',
  borderLeft: 0,
};

interface ServerSettingProps {
  dispatch?: Dispatch | any;
  forms: any;
  auth: string;
  detailInfo?:any;
  INITINFO?: any;
}

interface ServerSettingState {
  is_checkbox: boolean;
  isShare: number | string;
  isSendByDoor: boolean;
  sendByDoorTimes: any[];
}

@connect(({ common: { INITINFO } }: any) => ({ INITINFO }))

class ServerSettingElem extends Component<ServerSettingProps, ServerSettingState> {
  state: ServerSettingState = {
    is_checkbox: false,
    isShare: '',
    isSendByDoor: false,
    sendByDoorTimes: [''],
  };

  static getDerivedStateFromProps(nextProps: ServerSettingProps, perState: ServerSettingState) {
    const { isShare } = perState;
    const { detailInfo = {} } = nextProps;
    if (detailInfo.id && isShare !== detailInfo.isShare) {
      return {
        is_checkbox: !!detailInfo.isShare,
        isShare: detailInfo.isShare,
        isSendByDoor: !!detailInfo.sendByDoorStatus,
        sendByDoorTimes: detailInfo.reserveTime ? detailInfo.reserveTime.split(',') : [''],
      };
    }
    return null;
  }

  renderLogElem = (detailInfo: DetailInfoItem) => (
    <Card title="日志信息" bordered={false} className={styles.bodyStyle}>
      <Timeline>
        <Timeline.Item>最近操作人：{detailInfo.updateUserName}</Timeline.Item>
        <Timeline.Item>最近操作时间：{detailInfo.updateTime}</Timeline.Item>
        <Timeline.Item>创建人：{detailInfo.createUserName}</Timeline.Item>
        <Timeline.Item>创建时间：{detailInfo.createTime}</Timeline.Item>
      </Timeline>
    </Card>
  );

  handleChangeCheckbox = () => {
    const { is_checkbox } = this.state;
    this.setState({ is_checkbox: !is_checkbox });
  };

  /**
   * 是否上门取件
   */
  handleChangeSendByDoorStatus = (val: number) => this.setState({ isSendByDoor: !!val });

  /**
   * 选择上门取件时间
   */
  handleChangeReserveTime = (index: number, times: any) => {
    const { sendByDoorTimes } = this.state;
    const timesFormat = times
      ? `${moment(times[0]).format('HH:mm:ss')}-${moment(times[1]).format('HH:mm:ss')}`
      : '';
    sendByDoorTimes[index] = timesFormat;
    this.setState({ sendByDoorTimes });
  };

  /**
   * 新增一项上门取件时间
   */
  handleAddReserveTimeNum = () => {
    const { sendByDoorTimes } = this.state;
    const last = sendByDoorTimes[sendByDoorTimes.length - 1];
    if (!last) {
      message.error('请先完成选择上门取件时间');
    } else {
      this.setState({
        sendByDoorTimes: [...sendByDoorTimes, ''],
      });
    }
  };

  /**
   * 删除一项上门取件时间
   */
  handleDeleteReserveTimeNum = (index: number) => {
    const { forms: { resetFields } } = this.props;
    resetFields(['reserveTime']);

    const { sendByDoorTimes } = this.state;
    const new_sendByDoorTimes = [...sendByDoorTimes];
    new_sendByDoorTimes.splice(index, 1);
    this.setState({
      sendByDoorTimes: new_sendByDoorTimes,
    });
  };

  render() {
    const { is_checkbox, isSendByDoor, sendByDoorTimes = [] } = this.state;
    const {
      forms: { getFieldDecorator },
      detailInfo,
      INITINFO: { tariffList, passwordType },
      auth,
    } = this.props;

    const advanceNums = ['1天', '2天', '3天', '4天', '5天'];

    return (
      <Fragment>
        <Card title="服务设置" bordered={false}>
          <Row gutter={12}>
            <Col md={8} sm={24} style={{ marginBottom: 16 }}>
              {getFieldDecorator('isShare', {
                initialValue: detailInfo.isShare,
              })(
                <Checkbox
                  checked={is_checkbox}
                  disabled={detailInfo.id && auth !== 'root'}
                  onChange={this.handleChangeCheckbox}
                >
                  共享数据
                </Checkbox>,
              )}
            </Col>
          </Row>
          <Row gutter={12}>
            <Col md={8} sm={24}>
              <Item label="　　　收费套餐" colon={false}>
                {getFieldDecorator('tariffpkgId', {
                  initialValue: detailInfo.tariffpkgId,
                  rules: [{ required: true, message: '请选择收费套餐' }],
                })(
                  <Select
                    placeholder="请选择"
                    disabled={detailInfo.id && auth !== 'root'}
                  >
                    <Option value={0}>无</Option>
                    {tariffList.map((item: any) => (
                      <Option value={item.id} key={item.id}>{item.name}</Option>
                    ))}
                  </Select>,
                )}
              </Item>
            </Col>
            <Col md={8} sm={24}>
              <Item label="　　　是否启用" colon={false}>
                {getFieldDecorator('status', {
                  initialValue: detailInfo.status,
                  rules: [{ required: true, message: '请选择是否启用' }],
                })(
                  <Select
                    disabled={detailInfo.id && auth !== 'root'}
                    placeholder="请选择"
                  >
                    <Option value={1}>启用</Option>
                    <Option value={0}>禁用</Option>
                  </Select>,
                )}
              </Item>
            </Col>
          </Row>
          <Row gutter={12}>
            <Col md={8} sm={24}>
              <Item label="　　　密码类型" colon={false}>
                {getFieldDecorator('openCodeType', {
                  initialValue: detailInfo.openCodeType,
                  rules: [{ required: true, message: '请选择密码类型' }],
                })(
                  <Select
                    disabled={detailInfo.id && auth !== 'root'}
                    placeholder="请选择"
                  >
                    <Option value={0}>无</Option>
                    {passwordType.map((item: any) => (
                      <Option value={item.value} key={item.value}>{item.label}</Option>
                    ))}
                  </Select>,
                )}
              </Item>
            </Col>
            <Col md={8} sm={24}>
              <Item label="　　　门店寄件" colon={false}>
                {getFieldDecorator('sendByStoreStatus', {
                  initialValue: detailInfo.sendByStoreStatus,
                  rules: [{ required: true, message: '请选择门店寄件' }],
                })(
                  <Select
                    placeholder="请选择"
                    disabled={detailInfo.id && auth === 'other'}
                  >
                    <Option value={1}>开启</Option>
                    <Option value={0}>关闭</Option>
                  </Select>,
                )}
              </Item>
            </Col>
            <Col md={8} sm={24}>
              <Item label="门店寄件付款方式" colon={false}>
                {getFieldDecorator('initiatorPayer', {
                  initialValue: detailInfo.initiatorPayer || 1,
                  rules: [{ required: true, message: '请选择门店寄件付款方式' }],
                })(
                  <Select
                    placeholder="请选择"
                    disabled={detailInfo.id && auth === 'other'}
                  >
                    <Option value={1}>揽件员发起收款</Option>
                    <Option value={2}>寄件人主动发起付款</Option>
                  </Select>,
                )}
              </Item>
            </Col>
          </Row>
          <Row gutter={12}>
            <Col md={8} sm={24}>
              <Item label="　　　营业时间" colon={false}>
                {getFieldDecorator('serviceTime', {
                  initialValue: detailInfo.serviceTime && [
                    moment(detailInfo.serviceTime.split('-')[0], 'HH:mm:ss'),
                    moment(detailInfo.serviceTime.split('-')[1], 'HH:mm:ss'),
                  ],
                  rules: [{ required: true, message: '请选择营业时间' }],
                })(
                  <RangePicker
                    disabled={detailInfo.id && auth !== 'root'}
                    inputReadOnly
                    style={{ width: '100%' }}
                  />,
                )}
              </Item>
            </Col>
            <Col md={8} sm={24}>
              <Item label="　提前预约天数" colon={false}>
                {getFieldDecorator('reserveDay', {
                  initialValue: detailInfo.reserveDay || 0,
                  rules: [{ required: true, message: '请选择提前预约天数' }],
                })(
                  <Select
                    placeholder="请选择"
                    disabled={detailInfo.id && auth === 'other'}
                  >
                    <Option value={0}>只可当日</Option>
                    {advanceNums.map((item: string, index: number) => (
                      <Option value={index + 1} key={item}>
                        {item}
                      </Option>
                    ))}
                  </Select>,
                )}
              </Item>
            </Col>
            <Col md={8} sm={24}>
              <Item label="　收件人配置设置" colon={false}>
                {getFieldDecorator('isCheckConsigneeConf', {
                  initialValue: detailInfo.isCheckConsigneeConf || 0,
                  rules: [{ required: true, message: '请选择是否启用' }],
                })(
                  <Select placeholder="请选择" disabled={detailInfo.id && auth === 'other'}>
                    <Option value={1}>有效</Option>
                    <Option value={0}>无效</Option>
                  </Select>,
                )}
              </Item>
            </Col>
          </Row>
          <Row gutter={12}>
            <Col md={8} sm={24}>
              <Item label="　　　上门取件" colon={false}>
                {getFieldDecorator('sendByDoorStatus', {
                  initialValue: detailInfo.sendByDoorStatus || 0,
                  rules: [{ required: true, message: '请选择上门取件' }],
                })(
                  <Select
                    placeholder="请选择"
                    disabled={detailInfo.id && auth === 'other'}
                    onChange={this.handleChangeSendByDoorStatus}
                  >
                    <Option value={1}>开启</Option>
                    <Option value={0}>关闭</Option>
                  </Select>,
                )}
              </Item>
            </Col>
            {isSendByDoor
              && sendByDoorTimes.map((item: any, index: number) => (
                <Col md={8} sm={24} key={item} style={{ display: 'flex' }}>
                  <Item label="　　　上门时间" colon={false} style={{ flex: 1 }}>
                    {getFieldDecorator(`reserveTime[${index}]`, {
                      initialValue: item && [
                        moment(item.split('-')[0], 'HH:mm:00'),
                        moment(item.split('-')[1], 'HH:mm:00'),
                      ],
                      rules: [{ required: true, message: '请选择上门时间' }],
                    })(
                      <RangePicker
                        inputReadOnly
                        format="HH:mm:00"
                        disabled={detailInfo.id && auth === 'other'}
                        style={{ width: '100%' }}
                        onChange={(times: any) => this.handleChangeReserveTime(index, times)}
                      />,
                    )}
                  </Item>
                  {/* {index === 0 ? (
                    <PlusOutlined
                      style={reserveTimeBtn}
                      onClick={this.handleAddReserveTimeNum}
                    />
                  ) : (
                    <MinusOutlined
                      style={reserveTimeBtn}
                      onClick={() => this.handleDeleteReserveTimeNum(index)}
                    />
                  )} */}
                </Col>
              ))}
          </Row>
        </Card>

        {detailInfo.createTime && this.renderLogElem(detailInfo)}
      </Fragment>
    );
  }
}

export default ServerSettingElem;
